<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :form="form" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库">
              <j-popup
                v-decorator="['storeName']"
                :trigger-change="true"
                :list-data.sync="listData"
                org-fields="id,store_name"
                dest-fields="storeId,storeName"
                code="store_info"
                @callback="popupCallback"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="申请人">
              <j-popup
                v-decorator="['applyUserName']"
                :trigger-change="true"
                placeholder="请选择申请人"
                code="tj_user_report"
                org-fields="id,realname"
                dest-fields="applyUserId,applyUserName"
                @callback="popupCallback"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="补货单状态">
              <j-dict-select-tag
                placeholder="请选择补货单状态"
                v-model="queryParam.state"
                dictCode="replenish_goods_bill_status"
              />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus"> </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset1" icon="reload" style="margin-left: 8px">重置</a-button>
              <!--<a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'replenishment:add'">新增</a-button>

      <a-popover title="注意" placement="right" v-has="'replenishment:export'">
        <template slot="content">
          <p>请选择已通过或者已打印申请的补货单进行导出</p>
          <p style="color: #ff4000">
            *状态非<span style="color: #409eff">【已通过】【已打印】</span>的将不能被正确导出*
          </p>
        </template>
        <a-button
          type="primary"
          icon="download"
          @click="handleExportXlsBtn('补货单')"
          :disabled="selectedRowKeys.length ? false : true"
          >导出</a-button
        >
      </a-popover>
      <!--<a-button type="primary" icon="download" @click="handleExportXls('补货单')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          type: 'radio',
          hideDefaultSelections: true,
          onChange: onSelectChange,
        }"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="state_dictText" slot-scope="text, record">
          <div v-html="text" v-if="record.state == 0" style="color: #ff4000"></div>
          <div v-html="text" v-else-if="record.state == 1" style="color: #13c2c2"></div>
          <div v-html="text" v-else-if="record.state == 2" style="color: #ff8000"></div>
          <div v-html="text" v-else style="color: #00a0e9"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <span v-if="[0, 2].includes(record.state)" v-has="'replenishment:edit'">
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
          </span>
          <span v-if="record.state == 0" v-has="'replenishment:approval'">
            <a @click="handleAudit(record)">审核</a>
            <a-divider type="vertical" />
          </span>
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item v-has="'replenishment:detail'">
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <!-- <a-menu-item v-if="record.state!==3">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item> -->
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <replenish-goods-bill-modal ref="modalForm" @ok="modalFormOk1" />

    <!-- <a-modal
      title="审核"
      :visible="visible2"
      @cancel="handleCancel2"
    >
      <a-textarea
        v-model="AuditTxt"
        placeholder="审核意见"
        :auto-size="{ minRows: 3, maxRows: 5 }"
      />
      <template slot="footer">
        <a-button type="primary" @click="handleOk2" :loading="confirmLoading">
          同 意
        </a-button>
        <a-button  type="danger"  @click="handleCancel3" :loading="confirmLoading">
          拒 绝
        </a-button>
      </template>
    </a-modal> -->
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { downFile } from '@/api/manage'
import ReplenishGoodsBillModal from './modules/ReplenishGoodsBillModal'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import '@/assets/less/TableExpand.less'

export default {
  name: 'ReplenishGoodsBillList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    ReplenishGoodsBillModal,
  },
  data() {
    return {
      /*审核弹窗*/
      id: '',
      listData: null,
      visible2: false,
      AuditTxt: '', //审核意见
      confirmLoading: false,
      description: '补货单管理页面',
      form: this.$form.createForm(this),
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '仓库',
          align: 'center',
          dataIndex: 'storeName',
        },
        {
          title: '申请人',
          align: 'center',
          dataIndex: 'applyUserName',
        },
        {
          title: '补货单状态',
          align: 'center',
          dataIndex: 'state_dictText',
          scopedSlots: { customRender: 'state_dictText' },
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          // customRender: function (text) {
          //   return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          // },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          // fixed:"right",
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/order/replenishGoodsBill/list',
        delete: '/order/replenishGoodsBill/delete',
        deleteBatch: '/order/replenishGoodsBill/deleteBatch',
        exportXlsUrl: '/order/replenishGoodsBill/exportXls',
        importExcelUrl: 'order/replenishGoodsBill/importExcel',
        audit: '/order/replenishGoodsBill/audit', //审核
        exportXls: '/order/replenishGoodsBill/exportXls', //打印
      },
      dictOptions: {},
    }
  },
  created() {},
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  watch: {
    selectedRowKeys: {
      deep: true,
      immediate: true,
      handler(val) {
        console.log(val)
      },
    },
    listData: {
      immediate: true,
      handler(val) {
        if (val) {
          let row = {
            storeId: val[0].id,
            storeName: val[0].store_name,
          }
          this.popupCallback(row)
        }
      },
    },
  },
  methods: {
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
      // this.$refs.modalForm.disableSubmit = false;
    },
    //下载补货word
    handleExportXlsBtn(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        for (let i = 0; i < this.selectionRows.length; i++) {
          const item = this.selectionRows[i]
          if (this.selectedRowKeys[0] == item.id && [1, 3].includes(item.state)) {
            param['ids'] = this.selectedRowKeys[0]
          } else {
            this.$message.warning('补货单状态不可导出')
            return
          }
        }
      } else {
        this.$message.warning('请先选择要导出补货单')
        return
      }
      downFile(this.url.exportXls, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/msword' }), fileName + '.doc')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/msword' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.doc')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
          this.loadData()
        }
      })
    },
    initDictConfig() {},

    /*审核接口*/
    handleAudit(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '审核'
      this.$refs.modalForm.disableSubmit = true
    },
    popupCallback(row) {
      let type
      if (row.storeId !== undefined) {
        type = 'storeId'
      } else {
        type = 'applyUserId'
      }
      this.form.setFieldsValue(pick(row, 'storeName', 'applyUserName'))
      this.queryParam[type] = row[type]
    },
    searchReset1() {
      this.form.setFieldsValue({ storeName: '', applyUserName: '' })
      this.searchReset()
    },
    modalFormOk1() {
      this.modalFormOk()
      this.selectedRowKeys = []
      this.selectionRows = []
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.ant-btn-danger {
  background: #ff4d4f;
}

.ant-btn-danger:hover {
  background: #ff7875;
}
</style>